package org.example.api.admin;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baidubce.qianfan.Qianfan;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.example.R.R;
import org.example.entity.dto.ChatDTO;
import org.example.service.ExService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@Slf4j
@RestController
@RequestMapping("/api/admin/ex")
public class ExController {

    @Autowired
    private ExService exService;
    private final ExecutorService nonBlockingService = Executors.newCachedThreadPool();

    @PostMapping("/oss")
    public R OSS(@RequestParam("ossFile") MultipartFile ossFile) {
        return exService.uploadOSS(ossFile);
    }


    @PostMapping("/chat")
    public SseEmitter streamChat() {
        SseEmitter emitter = new SseEmitter();

        Gson gson = new Gson();
        Qianfan qianfan = new Qianfan("08fe22386e784b57943ce1f61df76ed6", "2fbaf2e167c6495ca5b47cf2fb9b25eb");


        qianfan.chatCompletion()
                .model("ERNIE-4.0-8K")
                .addMessage("user", "长治市2024年经济报告")
                .executeStream()
                .forEachRemaining(chunk -> {
                    try {
                        String jsonChunk = gson.toJson(chunk);
                        SseEmitter.SseEventBuilder event = SseEmitter.event()
                                .data("jsonChunk", MediaType.TEXT_PLAIN);
                        emitter.send(event);
                        Thread.sleep(1000);
                        emitter.complete();
                    } catch (IOException | InterruptedException e) {
                        emitter.completeWithError(e);
                    }
                });
        return emitter;
    }


    @PostMapping("/see")
    public SseEmitter handleSse(@RequestBody ChatDTO dto) {
        Gson gson = new Gson();
        Qianfan qianfan = new Qianfan("08fe22386e784b57943ce1f61df76ed6", "2fbaf2e167c6495ca5b47cf2fb9b25eb");

        SseEmitter emitter = new SseEmitter(0L); // 设置初始超时时间为0，表示不使用默认超时
        emitter.onCompletion(() -> log.info("SseEmitter completed"));
        emitter.onTimeout(() -> {
            log.warn("SseEmitter timed out");
            emitter.complete();
        });
        emitter.onError(error -> {
            log.error("Error occurred while sending SSE: {}", error.getMessage());
            emitter.completeWithError(error);
        });

        nonBlockingService.execute(() -> {
            qianfan.chatCompletion()
                    .model("ERNIE-4.0-8K")
                    .addMessage("user", dto.getContent())
                    .executeStream()
                    .forEachRemaining(chunk -> {
                        String jsonChunk = gson.toJson(chunk);
                        String result = new JSONObject(jsonChunk).getStr("result");
                        if (StrUtil.isNotBlank(result)) {
                            try {
                                SseEmitter.SseEventBuilder event = SseEmitter.event()
                                        .data(result, MediaType.TEXT_PLAIN);
                                emitter.send(event);
                                System.out.println(result);
                                Thread.sleep(200);
                            } catch (IOException e) {
                                emitter.completeWithError(e);
                            } catch (InterruptedException e) {
                                Thread.currentThread().interrupt(); // 恢复线程中断状态
                                emitter.completeWithError(e);
                            }
                        }
                    });
            emitter.complete();
        });

        return emitter;
    }


}
